<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图区域 -->
    <el-card>
      <!-- 搜索与添加区域 -->
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input placeholder="请输入内容" v-model="queryInfo.query" clearable @clear="getGoodsList">
            <el-button slot="append" icon="el-icon-search" @click="getGoodsList"></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="goAddPage">添加商品</el-button>
        </el-col>
      </el-row>

      <!-- 用户列表区域 -->
      <el-table :data="goodlist" border stripe>
        <el-table-column type="index"></el-table-column>
        <el-table-column label="商品名称" prop="goods_name" width="500px"></el-table-column>
        <el-table-column sortable label="商品价格" prop="goods_price" width="110px"></el-table-column>
        <el-table-column sortable label="商品重量" prop="goods_weight" width="110px"></el-table-column>
        <el-table-column label="创建时间"><template slot-scope="scope" >
            {{scope.row.add_time | dateFormat}}
        </template></el-table-column>
        <el-table-column label="操作" width="120px">
          <!-- eslint-disable-next-line vue/no-unused-vars -->
          <template slot-scope="scope">
            <!-- 修改按钮 -->
            <el-button type="primary" icon="el-icon-edit" size="mini" @click="editGoods(scope.row.goods_id)"></el-button>
            <!-- 删除按钮 -->
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="deletegood(scope.row.goods_id)"></el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页区域 -->
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="queryInfo.pagenum" 
      :page-sizes="[5, 10, 20, 50]" :page-size="queryInfo.pagesize" layout="total, sizes, prev, pager, next, jumper" :total="total">
      </el-pagination>
    </el-card>

    <!-- 修改的对话框 -->
    <el-dialog title="修改商品信息" :visible.sync="editDialogVisible" 
    width="50%" @close="editDialogClosed">
      <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="100px">
        <el-form-item label="商品id" prop="goods_id">
          <el-input v-model="editForm.goods_id" disabled></el-input>
        </el-form-item>
        <el-form-item label="商品名称" prop="goods_name">
          <el-input v-model="editForm.goods_name"></el-input>
        </el-form-item>
        <el-form-item label="商品价格" prop="goods_price">
          <el-input v-model="editForm.goods_price" type="number"></el-input>
        </el-form-item>
        <el-form-item label="商品数量" prop="goods_number">
          <el-input v-model="editForm.goods_number" type="number"></el-input>
        </el-form-item>
        <el-form-item label="商品重量" prop="goods_weight">
          <el-input v-model="editForm.goods_weight" type="number"></el-input>
        </el-form-item>
        <el-form-item label="商品描述">
          <el-input type="textarea" :row="2" placeholder="请输入对商品的描述"></el-input>
        </el-form-item>
        <el-form-item label="商品状态" prop="goods_state">
          <el-input v-model="editForm.goods_state" disabled></el-input>
        </el-form-item>
        <el-form-item label="更新时间" prop="upd_time">
          <el-input v-model="updataTime" disabled></el-input>
        </el-form-item>
        <el-form-item label="热销品数量" prop="hot_mumber">
          <el-input v-model="editForm.hot_mumber" type="number" disabled></el-input>
        </el-form-item>
        <el-form-item label="是否是热销品" prop="is_promote">
          <el-input v-model="isPromote" disabled></el-input>
        </el-form-item>
        <el-upload
        action="http://127.0.0.1:8888/api/private/v1/upload"
        :headers="headerObj"
        :on-preview="handlePreview"
        :on-remove="handleRemove"
        :on-success="handelSuccess"
        :file-list="fileList"
        list-type="picture">
        <el-button size="small" type="primary">点击上传</el-button>
      </el-upload>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editGoodsInfo">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    var checkPrice = (rule, value, callback) => {
        if (!value) {
          return callback(new Error('不能为0或空值'));
        }
      };
    return {
      goodlist:[],
      queryInfo:{
        query:'',
        pagenum:1,
        pagesize:10
      },
      total:0,
      editDialogVisible:false,
      editForm:{

      },
      editFormRules:{
        goods_name:[
            { required: true, message: '请输入', trigger: 'blur' },
            {
                min: 1,
                max: 10,
                message: '长度在1~10个字符之间',
                trigger: 'blur'
            }
        ],
        goods_price:[
            { required: true, message: '请输入', trigger: 'blur' },
            { validator: checkPrice, trigger: 'blur' }
        ],
        goods_weight:[
            { required: true, message: '请输入', trigger: 'blur' },
            { validator: checkPrice, trigger: 'blur' }
        ],
        goods_number:[
            { required: true, message: '请输入', trigger: 'blur' },
            { validator: checkPrice, trigger: 'blur' }
        ]
      },
      headerObj:{
            Authorization:window.sessionStorage.getItem("token")
      },
      fileList:[]
    }
  },
  created() {
    this.getGoodsList()
  },
  methods: {
    async getGoodsList(){
      const {data:res} = await this.$http.get('goods',{params:this.queryInfo})
      if(res.meta.status != 200) return this.$message.error('获取商品列表数据失败')
      //this.$message.success('获取商品列表数据成功')
      console.log(res.data)
      this.goodlist = res.data.goods;
      this.total = res.data.total;

    },
    handleSizeChange(val){
      this.queryInfo.pagesize = val;
      this.getGoodsList()
    },
    handleCurrentChange(val){
      this.queryInfo.pagenum = val;
      this.getGoodsList()
    },
    deletegood(gid){
        this.$confirm('此操作将永久删除, 是否继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
            }).then(async () => {
            const {data:res} = await this.$http.delete(`goods/${gid}`);
            if(res.meta.status != 200) return this.$message.error('删除失败')
            this.$message.success('删除成功');
            this.getGoodsList();   
            }).catch((err) => {
              console.log(err)
            this.$message({
                type: 'info',
                message: '已取消删除'
            });          
            });
      },
      goAddPage(){
        this.$router.push('goods/add')
      },
      async editGoods(goodsId){
        const {data:res} = await this.$http.get(`goods/${goodsId}`)
        if(res.meta.status != 200) return this.$message.error('获取该商品信息失败，请重新尝试')
        this.editForm = res.data;
        res.data.pics.forEach(item =>{
          const imgInfo = {
            name:item.pics_id,
            url:item.pics_big
          }
          this.fileList.push(imgInfo)
        })
        this.editDialogVisible = true;
      },
      editDialogClosed(){
        this.$refs.editFormRef.resetFields()
      },
      editGoodsInfo(){
        this.$refs.editFormRef.validate(async valid =>{
          if(!valid) return;
          const {data:res} = await this.$http.put(`goods/${this.editForm.goods_id}`)
          if(res.meta.status != 200) return this.$message.error('修改失败')
          this.$message.success('修改成功')
          this.getGoodsList()
          this.editDialogVisible = false;
        })
      },
      handlePreview(file){
        console.log(file)
      },
      handleRemove(file){
        console.log(file)
      },
      handelSuccess(response){
        console.log(response)
      }
  },
  components: {

  },
  computed:{
    updataTime(){
      const dt = new Date(this.editForm.upd_time);
      var Y = dt.getFullYear();
      var M = (dt.getMonth()+1+'').padStart(2,'0');
      var D = (dt.getDate()+'').padStart(2,'0');
      var H = (dt.getHours()+'').padStart(2,'0');
      var Min = (dt.getMinutes()+'').padStart(2,'0');
      var s = (dt.getSeconds()+'').padStart(2,'0');

      return `${Y}-${M}-${D} ${H}:${Min}:${s}`
    },
    isPromote(){
      return this.editForm.is_promote ? '是':'否'
    }
  }
}
</script>

<style lang='less' scoped>

</style>
